<!-- 自定义告警指标配置 -->
<template>
	<div class="container">
		<!-- 搜索条件 -->
		<yd-form class="yd-form-wraper" :model="formData" :options="formOptions">
			<template #form-btn>
				<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
			</template>
		</yd-form>

		<!--查询列表-->
		<YdTable
			:formData="formData"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			ref="multipleTable"
			@sizeChangeHandler="searchHandler"
			@currentChangeHandler="getData"
			@sortChangeHandler="getData"
			@selectionChangeHandler="handleSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="title" v-model="open" width="900px" append-to-body center @close="cancel" :close-on-click-modal="false">
			<el-form ref="conForm" :model="form" :rules="rules" label-width="200px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="指标名称:" prop="name">
							<el-input v-model="form.name" placeholder="请输入指标名称" :disabled="updateDisabled" style="width: 200px" maxlength="50" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="颗粒度:" prop="particleId">
							<el-select v-model="form.particleId" placeholder="请选择" :disabled="updateDisabled">
								<el-option v-for="dict in particleOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="指标单位:" prop="unit">
							<el-select v-model="form.unit" placeholder="请选择" :disabled="inputReadOnly">
								<el-option v-for="dict in unitOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="指标对象:" prop="objId">
							<el-select v-model="form.objId" placeholder="请选择" :disabled="updateDisabled" @change="indicatorChangeHandle">
								<el-option v-for="dict in objOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="指标说明:">
							<el-input v-model="form.description" type="textarea" placeholder="请输入指标说明" :disabled="inputReadOnly" maxlength="200"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="表达式:" prop="expression">
							<el-input
								v-model="form.expression"
								type="textarea"
								placeholder="请输入表达式"
								rows="5"
								ref="expression"
								:disabled="inputReadOnly"
								maxlength="300"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="showSubmit">
					<el-col :span="24" align="center" style="margin-left: 100px">
						<el-button @click="countHandle">COUNT()</el-button>
						<el-button @click="sumHandle">SUM()</el-button>
						<el-button @click="avgHandle">AVG()</el-button>
						<el-button @click="showCodeHandle">插入指标编码</el-button>
						<el-button @click="expressionHandle">表达式验证</el-button>
					</el-col>
				</el-row>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="submitForm" v-if="showSubmit">确 定</el-button>
				<el-button @click="cancel" v-if="showSubmit">取 消</el-button>
				<el-button type="primary" @click="cancel" v-if="showClose">关 闭</el-button>
			</template>
		</el-dialog>

		<!-- 指标编码对话框 -->
		<el-dialog title="指标编码" v-model="openVariable" width="700px" center>
			<div id="codeHeadDiv">指标对象关联的表：{{ indicatorObjRelationTable }}</div>
			<div style="height: 500px">
				<el-table :data="codeList" ref="singleTable" height="500px" highlight-current-row @selection-change="handleIndicatorSelect">
					<el-table-column type="selection" align="center" />
					<el-table-column type="index" label="序号" align="center" width="60px" />
					<el-table-column label="指标编码" align="center" prop="code" />
					<el-table-column label="说明" align="center" prop="name" />
				</el-table>
			</div>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="handleAddCodeConfirm">确 认</el-button>
				<el-button @click="variableCancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="AlarmAdvancedIndicator" lang="tsx">
import { ref, reactive, getCurrentInstance, ComponentInternalInstance, onMounted, toRefs, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import {
	queryAdvancedIndicatorsList,
	queryIndicatorById,
	queryCodeList,
	addAdvancedIndicator,
	editAdvancedIndicator,
	editCustomIndicatorsEnable,
	deleteIndicatorsByIds,
	queryAlarmByIndicatorId,
	checkExpression,
} from '@/api/management/alarmManage/alarmIndicator';
import { queryUnitList } from '@/api/management/alarmManage/alarmIndicatorUnit';
import { queryDictByType } from '@/api/search/searchOptions';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { forEach } from 'lodash';

// const instance = getCurrentInstance() as ComponentInternalInstance;
// const proxy = instance?.appContext.config.globalProperties;
const { proxy } = useCurrentInstance();

nextTick(() => {
	console.log('proxy-------------', proxy);
});
const router = useRouter();

const statusOptions = ref([
	{ label: '是', value: 0 },
	{ label: '否', value: 1 },
]);
// 总条数
const total = ref(0);
// 遮罩层
const loading = ref(true);
const unitOptions = ref<any[]>([]);
const objOptions = ref<any[]>([]);
const particleOptions = ref<any[]>([]);
//指标编码列表
const codeList = ref<any[]>();
//指标对象关联的bpm表名
const indicatorObjRelationTable = ref('');
// 选中数组
const ids = ref<any[]>([]);
// 选中状态数组
const enables = ref<any[]>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref('');
// 表单参数
const data = reactive<anyObj>({
	form: {},
});
const { form } = toRefs(data);
// 是否显示弹出层
const open = ref(false);
const openVariable = ref(false);
//修改禁用类型和名称不能修改
const updateDisabled = ref(false);
//是否显示确认提交按钮，查看详情的时候不需要确认按钮
const showSubmit = ref(true);
const showClose = ref(false);
const inputReadOnly = ref(false);
//弹窗指标编码对象
//codeObj: {},
// 弹框指标编码选中数组
const singleTableSelection = ref<any[]>([]);
// 表单校验
const rules = ref({
	name: [{ required: true, message: '指标名称不能为空', trigger: 'blur' }],
	unit: [{ required: true, message: '指标单位不能为空', trigger: 'change' }],
	objId: [{ required: true, message: '指标对象不能为空', trigger: 'change' }],
	expression: [{ required: true, message: '表达式不能为空', trigger: 'blur' }],
	particleId: [{ required: true, message: '颗粒度不能为空', trigger: 'change' }],
});
// 表格的实例
const multipleTable = ref();
// 表单的实例
const conForm = ref();

// 搜索表单数据
let formData = reactive<FormModelType>({
	pageNum: 1,
	pageSize: 10,
});

// 表单项配置
const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		label: '是否启用',
		prop: 'isEnable',
		placeholder: '请选择是否禁用',
		isInitValue: false,
		children: [
			{ label: '是', value: 0 },
			{ label: '否', value: 1 },
		],
	},
	{
		type: 'input',
		label: '指标名称',
		prop: 'name',
	},
]);

// 列表数据
let tableData = reactive({
	data: [],
});
// 列表配置
let tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '指标名称',
			prop: 'name',
			width: 230,
		},
		{
			label: '颗粒度',
			prop: 'particleName',
			width: 120,
		},
		{
			label: '指标单位',
			prop: 'unitName',
			width: 120,
		},
		{
			label: '指标对象',
			prop: 'indicatorsObject',
			width: 120,
		},
		{
			label: '表达式',
			prop: 'expression',
		},
		{
			label: '启用状态',
			prop: 'isEnable',
			width: 120,
			render: (row, val) => {
				if (proxy?.checkPermi(['alarmIndicator:enable'])) {
					return (
						<el-switch
							v-model={row.isEnable}
							activeValue={0}
							inactiveValue={1}
							onChange={() => {
								console.log('cahnge--------', row);
								handleEnableChange(row);
							}}
						></el-switch>
					);
				}
				return <el-switch v-model={row.isEnable} disabled activeValue={0} inactiveValue={1}></el-switch>;
			},
		},
		{
			label: '操作',
			prop: '',
			width: 100,
			operation: [
				{
					text: '详情',
					handler: (scope) => getDetailHandle(scope.row),
				},
				{
					text: '告警',
					handler: (scope) => jumpToAdvanceAlarmHandle(scope.row),
					permi: ['alarmIndicator:list'],
				},
			],
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['alarmIndicator:add'], handler: () => handleAdd() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['alarmIndicator:edit'], disable: 'single', handler: () => handleUpdate() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['alarmIndicator:delete'], disable: 'multiple', handler: () => handleDelete() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
	},
	// 加载层
	loading: true,
});

onMounted(() => {
	queryUnitList().then((res: ApiResponse) => {
		if (res.code === 0) {
			unitOptions.value = res.data || [];
			unitOptions.value.forEach((item: any) => {
				item.value = Number(item.value);
			});
		}
	});
	//从数据字典里面查询告警对象
	queryDictByType('sys_alarm_particle_type').then((res: ApiResponse) => {
		let data = res.data;
		for (var i = 0; i < data.length; i++) {
			let temp: anyObj = {};
			temp.value = Number(data[i].value);
			temp.label = data[i].label;
			particleOptions.value.push(temp);
		}
	});
	//从数据字典里面指标对象
	queryDictByType('conf_alarm_indicator_obj_type').then((res: ApiResponse) => {
		let data = res.data;
		for (var i = 0; i < data.length; i++) {
			let temp: anyObj = {};
			temp.value = parseInt(data[i].value);
			temp.label = data[i].label;
			objOptions.value.push(temp);
		}
	});
});

function searchHandler() {
	tableConfig.pagination!.pageNum = 1;
	nextTick(() => {
		getData();
	});
}

// 搜索
function getData() {
	tableConfig.loading = true;
	queryAdvancedIndicatorsList(formData).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			return;
		}
		tableData.data = res.data.records;
		tableData.data.forEach((item: any) => {
			if (item.isEnable === null) {
				item.isEnable = 1;
			}
		});
		tableConfig.pagination!.total = res.data.total;
	});
}
// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
	enables.value = selection.map((item: any) => item.isEnable);
}
// 指标编码列表选择
function handleIndicatorSelect(selection: any) {
	singleTableSelection.value = selection;
}
// 禁用启用
function handleEnableChange(row: any) {
	queryAlarmByIndicatorId(row.id).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			loading.value = false;
			return;
		}
		let dm = res.data;
		let dmStr = '';
		if (dm != null && dm != '') {
			dmStr = '禁用后这些告警都不再产生！：' + dm;
		}
		const data = {
			isEnable: row.isEnable,
			id: row.id,
		};
		//本来是启用状态，现在禁用
		if (row.isEnable == 1) {
			//在模版禁用时，需要查询m_alarms表里面是否有引用该模版，如果有需提示哪些告警引用到该模版，需解绑关系后才能禁用模版。
			let text = row.name;
			proxy.$modal
				.confirm('确认要禁用 ' + text + ' 吗?' + dmStr, '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					cancelButtonClass: 'confirm-rigth-cancel-button',
					type: 'warning',
				})
				.then(function () {
					return editCustomIndicatorsEnable(data);
				})
				.then(() => {
					proxy.$modal.msgSuccess('禁用 ' + text + '成功');
				})
				.catch(function () {
					row.isEnable = row.isEnable === 0 ? 1 : 0;
				});
		} else {
			editCustomIndicatorsEnable(data).then((res) => {
				if (res.code !== 0) {
					proxy.$modal.msgWarning(res.msg);
					loading.value = false;
					return;
				}
				proxy.$modal.msgSuccess('启用成功');
			});
		}
	});
	nextTick(() => {
		multipleTable.value?.getTableRef().clearSelection();
	});
	ids.value = [];
	enables.value = [];
}
/** 新增按钮操作 */
function handleAdd() {
	reset();
	title.value = '增加自定义告警指标';
	open.value = true;
	updateDisabled.value = false;
	showSubmit.value = true;
	showClose.value = false;
	inputReadOnly.value = false;
}
/** 修改按钮操作 */
function handleUpdate() {
	reset();
	title.value = '修改自定义告警指标';
	updateDisabled.value = true;
	open.value = true;
	showSubmit.value = true;
	showClose.value = false;
	inputReadOnly.value = false;
	const id: any = ids.value;
	if (id == null || id == '') {
		proxy.$modal.msgWarning('请选择要修改的自定义告警指标。');
		return;
	}
	queryIndicatorById(id).then((res: ApiResponse) => {
		let data = res.data;
		if (data) {
			form.value = {
				...data,
				// unitId: data.unit,
			};
		}

		indicatorChangeHandle(form.value.objId);
	});
}
/** 删除按钮操作 */
function handleDelete(row?: any) {
	if (row != null) {
		if (row.id != null) {
			ids.value = [];
			ids.value.push(row.id);
		}
		if (row.isEnable != null) {
			enables.value = [];
			enables.value.push(row.isEnable);
		}
	}
	if (ids.value == null) {
		proxy.$modal.msgWarning('请选择要删除的自定义告警指标。');
		return;
	}
	if (enables.value.length > 0) {
		for (let i = 0; i < enables.value.length; i++) {
			if (enables.value[i] === 0) {
				proxy.$modal.msgWarning('只能删除已经禁用的指标！');
				return;
			}
		}
	}
	proxy.$modal
		.confirm('是否需要删除已经勾选的指标数据?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(function () {
			return deleteIndicatorsByIds(ids.value);
		})
		.then(() => {
			getData();
			proxy.$modal.msgSuccess('删除成功');
		})
		.catch(() => {});
}
/** 提交按钮 */
function submitForm() {
	conForm.value?.validate((valid: any) => {
		if (valid) {
			//新增或者修改提交前先校验表达式
			if (form.value.id != undefined) {
				editAdvancedIndicator(form.value).then((res) => {
					if (res.code === 0) {
						proxy.$modal.msgSuccess('修改成功');
						open.value = false;
						getData();
					} else {
						proxy.$modal.msgWarning(res.msg);
						return;
					}
				});
			} else {
				addAdvancedIndicator(form.value).then((res) => {
					if (res.code === 0) {
						proxy.$modal.msgSuccess('新增成功');
						open.value = false;
						getData();
					} else {
						proxy.$modal.msgWarning(res.msg);
						return;
					}
				});
			}
		}
	});
}
// 取消按钮
function cancel() {
	open.value = false;
	singleTableSelection.value = [];
	reset();
}
// 表单重置
function reset() {
	form.value = {
		unitId: undefined,
		name: undefined,
		description: undefined,
		objId: undefined,
		expression: undefined,
	};
	conForm.value?.resetFields();
}
function showCodeHandle() {
	if (form.value.objId == null || form.value.objId == '') {
		proxy.$modal.msgWarning('请先选择指标对象');
		return;
	}
	openVariable.value = true;
	codeList.value = [];
	//从数据字典里面查询指标编码
	queryCodeList(form.value.objId).then((res: ApiResponse) => {
		codeList.value = res.data;
	});
}
// 取消指标编码弹出窗按钮
function variableCancel() {
	openVariable.value = false;
}
function countHandle() {
	if (form.value.expression == null) {
		form.value.expression = 'COUNT()';
	} else {
		form.value.expression = form.value.expression + 'COUNT()';
	}
	//每次清理验证信息
	conForm.value?.clearValidate('expression');
}
function sumHandle() {
	if (form.value.expression == null) {
		form.value.expression = 'SUM()';
	} else {
		form.value.expression = form.value.expression + 'SUM()';
	}
	//每次清理验证信息
	conForm.value?.clearValidate('expression');
}
function avgHandle() {
	if (form.value.expression == null) {
		form.value.expression = 'AVG()';
	} else {
		form.value.expression = form.value.expression + 'AVG()';
	}
	//每次清理验证信息
	conForm.value?.clearValidate('expression');
}
//编码弹窗选中处理
/*function handleCurrentChange(val) {
    codeObj = {};
    codeObj = val;
}*/
//编码弹窗确认按钮处理
function handleAddCodeConfirm() {
	if (singleTableSelection.value.length <= 0) {
		proxy.$modal.msgWarning('请选择一个指标编码！');
		return;
	} else {
		let codeObjStr = '';
		if (singleTableSelection.value.length > 0) {
			singleTableSelection.value.forEach((item) => {
				codeObjStr = codeObjStr + '' + item.code;
			});
			if (form.value.expression == null) {
				form.value.expression = codeObjStr;
			} else {
				form.value.expression = form.value.expression + '' + codeObjStr;
			}
		}
	}
	//每次清理验证信息
	conForm.value?.clearValidate('expression');
	openVariable.value = false;
}
/*function handleCodeRowClick(row, column, event) {
    codeObj = {};
    codeObj = val;
    if (form.value.expression == null) {
        form.value.expression = codeObj.code;
    } else {
        form.value.expression = form.value.expression + "" + codeObj.code;
    }
    openVariable.value = false;
    //每次清理验证信息
    proxy.$refs["conForm"].clearValidate("expression");
}*/
//表达式校验
function expressionHandle() {
	if (form.value.expression == null) {
		proxy.$modal.msgWarning('请输入表达式！');
		return;
	} else if (form.value.objId == null) {
		proxy.$modal.msgWarning('请选择一个指标对象！');
		return;
	}

	checkExpression(form.value).then((res) => {
		if (res.code === 0) {
			proxy.$modal.msgSuccess('校验成功');
		} else {
			proxy.$modal.msgWarning(res.msg);
		}
	});
}
//点击跳转到自定义告警页面
function jumpToAdvanceAlarmHandle(row: any) {
	router.push({
		path: '/management/alarmManage/customAlarmConfig',
		query: {
			alarmIndicatorId: row.id,
		},
	});
}
//点击查看详情
function getDetailHandle(row: any) {
	reset();
	title.value = '自定义告警指标配置详情';
	open.value = true;
	showSubmit.value = false;
	showClose.value = true;
	inputReadOnly.value = true;
	updateDisabled.value = true;
	const id = row.id;
	queryIndicatorById(id).then((res: ApiResponse) => {
		let data = res.data;
		if (data) {
			form.value = {
				...data,
				unitId: data.unit,
			};
		}
	});
}
//指标对象下拉选择触发
function indicatorChangeHandle(data: any) {
	//系统
	if (data == 1) {
		indicatorObjRelationTable.value = 'busi_sys_req_trend_m';
	} else if (data == 2) {
		indicatorObjRelationTable.value = 'busi_detail_stat_m';
	} else if (data == 3) {
		indicatorObjRelationTable.value = 'busi_sys_segment_trend_m';
	}
}
getData();
</script>

<style lang="scss" scoped>
.container {
	margin: 10px;
}

#codeHeadDiv {
	height: 18px;
	font-size: 18px;
	margin-bottom: 10px;
}
</style>
